package com.io.nettyflow.server;

import com.io.nettyflow.serverHandler.VtChannelInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * Created by yangyx on 2016/7/21.
 * Vts使用的服务端
 */
public class VtsServer {

/*
    public static void main(String[] args){
        int port=5555;
        new VtsServer().bind(port);
    }*/
    public void bind(int port){
        EventLoopGroup singleEventLoopGroup = new NioEventLoopGroup();
        ServerBootstrap bootstrap = new ServerBootstrap();
        try {
            //这里我只安排了一个EventLoopGroup,很多地方这里搞了两个,一个Boss,一个Worker,我看也没太多差别
            bootstrap.group(singleEventLoopGroup);
            bootstrap.channel(NioServerSocketChannel.class);
            //Setup the maximum queue length for incoming connection indications (a request to connect) is set to the backlog parameter.
            //If a connection indication arrives when the queue is full, the connection is refused.
            bootstrap.option(ChannelOption.SO_BACKLOG, 1024);
            //初始化的ChannelHandler
            bootstrap.childHandler(new VtChannelInitializer());
            ChannelFuture listenChannelFuture = bootstrap.bind(port).sync();
            System.out.println("Server started. Listening at port : " + port);
            //等待监听端口关闭,程序阻塞这里
            listenChannelFuture.channel().closeFuture().sync();
        }
        catch (Exception ex){
            System.out.println("Server bind failed.======"+ex);
        }
        finally {
            singleEventLoopGroup.shutdownGracefully();
        }

    }

}
